import Vue from 'vue'
import App from './App'
import router from './router'
import Axios from 'axios'
import Vant from 'vant'
import AwesomePicker from 'vue-awesome-picker'
import * as dd from 'dingtalk-jsapi'
import 'vant/lib/index.css'
import Api from './config/api'
import FastClick from 'fastclick'
import qs from 'qs'
Vue.prototype.dd = dd
window.addEventListener('load', function () {
  FastClick.attach(document.body)
}, false)

Axios.defaults.baseURL = process.env.VUE_APP_API
Axios.interceptors.request.use((config) => {
  // config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  // config.headers.Accept = 'application/json, text/plain, */*'
  const token = window.sessionStorage.getItem('token')
  config.params = config.params ? config.params : {};
  config.params = JSON.parse(JSON.stringify(config.params));
  if (token) {
      config.params['auth_access_token'] = token;
  }
  // if (token) {
  //   config.headers.Authorization = `Bearer ${token}`// 让每个请求携带自定义 token 请根据实际情况自行修改
  // }
  // 在请求发送之前做一些处理
  if (config.method === 'post') {// post
    config.data = config.data ? config.data : {};
    config.data = JSON.parse(JSON.stringify(config.data));

    config.data = qs.stringify(config.data);
}
  return config
}, err => Promise.reject(err))
// 响应拦截
Axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 400:
          // 返回 400 清除token信息并跳转到登录页面 全局配置刷新token
          router.push('/login')
          break
        case 401:
          // 返回 401 清除token信息并跳转到登录页面 全局配置刷新token
          router.push('/login')
          break
      }
    }
    return Promise.reject(error)
  }
)

/*Axios.defaults.transformRequest = [(data) => {
  let ret = ''
  for (const it in data) {
    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  }
  return ret
}]*/
Vue.use(Vant)
Vue.use(AwesomePicker)
Vue.prototype.baseUrl = Axios.defaults.baseURL
Vue.prototype.$http = Axios
Vue.prototype.api = Api
Vue.config.productionTip = false

router.beforeEach((to, from, next) => {
  if (to.path === '/login') next()
  else {
    let token = window.sessionStorage.getItem('token')
    if (token && token !== 'undefined') {
      next()
    } else {
      next({ name: 'login' })
    }
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
